<?php

/**
 * toefl API
 * Created by PhpStorm.
 * User: obelisk
 */

namespace app\modules\cn\controllers;

use app\libs\Speak;
use app\libs\Write;
use app\modules\content\models\Teachers;
use app\modules\content\models\Active;
use yii;
use app\libs\IeltsController;
use app\libs\Method;
use app\libs\Pager;
use app\libs\VerificationCode;
use app\libs\Sms;
use app\modules\cn\models\ResourcesPhone;
use app\modules\content\models\Banner;
use app\modules\content\models\Calendar;
use app\modules\content\models\Examroom;
use app\modules\content\models\Info;
use app\modules\content\models\Classes;
use app\modules\cn\models\User;
use app\modules\cn\models\Login;
use app\modules\cn\models\News;
use app\modules\cn\models\ExamMessage;
use UploadFile;
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';

if($origin==false)$origin='*';

header("Access-Control-Allow-Origin:$origin");

header('Access-Control-Allow-Headers: X-Requested-With');
header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
header("Access-Control-Allow-Credentials: true");

class ApiController extends IeltsController
{

    public $enableCsrfValidation = false;

    function init (){
        parent::init();
        include_once($_SERVER['DOCUMENT_ROOT'].'/../libs/ucenter/ucenter.php');
    }

    /**
     * 课程剩余数减1
     * By yanni
     */
    public function actionRand()
    {
        $id = \Yii::$app->request->get('id');
        $detail = Banner::find()->asArray()->where('id=' . $id)->one();
        if ($detail != false && $detail['viewCount']>0) {
            Banner::updateAll(['viewCount' => ($detail['viewCount'] - 1)], "id=$id");
        }
        $detail = Banner::find()->asArray()->where('id=' . $id)->one();
        die(json_encode(['code'=>1,'detail'=>$detail]));
    }

    /**
     * 短信接口
     * @sjeam
     */
    public function actionPhoneCode()
    {
        $session = Yii::$app->session;
        $sms = new Sms();
        $phoneNum = Yii::$app->request->post('phone');
        if (!empty($phoneNum)) {
            $phoneCode = mt_rand(100000, 999999);
            $session->set($phoneNum . 'phoneCode', $phoneCode);
            $session->set('phoneTime', time());
            $content = '申友网验证码：' . $phoneCode . '（10分钟有效），您正在通过手机号进行验证';
            $sms->send($phoneNum, $content, $ext = '', $stime = '', $rrid = '');
            $res['code'] = 1;
            $res['message'] = '短信发送成功！';
        } else {
            $res['code'] = 0;
            $res['message'] = '发送失败!手机号码为空！';
        }
        die(json_encode($res));
    }

    /**
     * 客户留言
     * @return string
     * @Obelisk
     */
    public function actionLeaveWords(){
        $phone = Yii::$app->request->post('phone');
        $code = Yii::$app->request->post('code');
        $remark = Yii::$app->request->post('remark');
        $wechat = Yii::$app->request->post('wechat','');
        $checkTime = Method::checkTime();
        if(!$checkTime){
            $res['code'] = 0;
            $res['message'] = '验证码过期';
        }else{
            $checkCode = Method::checkCode($phone,$code);
            if(!$checkCode){
                $res['code'] = 0;
                $res['message'] = '验证码错误';
            }else{
                $download =new ResourcesPhone();
                $download ->phone = $phone ;
                $download ->wechat = !empty($wechat)?$wechat:'' ;
                $download ->type = 2 ;
                $download ->createTime = time() ;
                $download ->remark = $remark;
                $download->save();
                $res['code'] = 1;
                $res['message'] = '我们的工作人员将于1-2个工作日内跟你联系';
            }
        }
        die(json_encode($res));
    }

    public function actionSearch()
    {
        $keyword = Yii::$app->request->get('keyword', '');
        if (strstr($keyword, '课') || strstr($keyword, '班')) {
            //重定向浏览器
            header("Location:/mall.html");
            //确保重定向后，后续代码不会被执行
            exit;
        }else{
            //重定向浏览器
            header("Location: /news.html");
            //确保重定向后，后续代码不会被执行
            exit;
        }
    }

    /**
     * 发送考位信息
     */
    public function actionSendPlace()
    {
        $session = Yii::$app->session;
        $sms = new Sms();
        $phone = Yii::$app->request->post('phone');
        $id = Yii::$app->request->post('id');//考位的id
        if (!empty($phone)) {
            $data = Examroom::find()->asArray()->where("id=$id")->one();//全部
            $download = new ResourcesPhone();
            $download->phone = $phone;
            $download->type = 2;
            $download->createTime = time();
            $download->remark = '查询雅思' . $data['city'] . '考场信息';
            $download->save();
            $content = '您好，欢迎使用申友雅思' . $data['city'] . '地区考点信息查询，以下是您所查询的内容：
考点代码：' . $data['code'] . '，
考点名称：' . $data['name'] . '，
地址：' . $data['address'] . '，
笔试考试：' . $data['writtenExam'] . '，
口试考场：' . $data['spokenExam'] . '，
电话：' . $data['phone'] . '，
交通：' . $data['traffic'] . '。
感谢您的使用，如有更多疑问，可拨打申友雅思全国免费咨询热线：400-600-1123
';
            $sms->send($phone, $content, $ext = '', $stime = '', $rrid = '');
            $res['code'] = 1;
            $res['message'] = '短信发送成功！';
        } else {
            $res['code'] = 0;
            $res['message'] = '发送失败!手机号码为空！';
        }
        die(json_encode($res));
    }

    public function actionGetDate()
    {
        $year = date('Y', time());
        $data = array();
        for ($i = 1; $i <= 12; $i++) {
            $data[$i - 1] = Calendar::find()->asArray()->where("year=$year and month=$i")->limit(31)->orderBy('date asc')->all();
        }
        die(json_encode(['code'=>1,'data'=>$data]));
    }

    /**
     * 搜索考场
     */
    public function actionSearchPlace()
    {
        $keyword = Yii::$app->request->post('keyword');
        $data = Examroom::find()->distinct()->asArray()->where("city like '%$keyword%' or name like '%$keyword%'")->all();//全部
        $res['code'] = 1;
        $res['data'] = $data;
        die(json_encode($res));
    }




    /**
     * 点击获取验证码
     * @sjeam
     */
    public function actionVerificationCode(){
        $_vc = new VerificationCode();  //实例化一个对象
        $_vc->doimg();
        Yii::$app->session->set('verificationCode',$_vc->getCode());//验证码保存到SESSION中
    }


    /**
     * 留学app首页的雅思资讯列表
     * yoyo
     */
    public function actionIeltsInfoList()
    {
        $cate = \Yii::$app->request->get('cate', 1);//123都是资讯 4是公开课
        $page = \Yii::$app->request->get('page', 1);
        $pageSize = \Yii::$app->request->get('pageSize', 10);
        $offset = $pageSize * ($page - 1);
        $time = time();
        $list = Info::find()->asArray()->where("(pushTime<=$time or pushTime is null) and cate=" . $cate)->offset($offset)->limit($pageSize)->orderBy('id desc')->all();
        die(json_encode(['code' => 1, 'data' => ['list' => $list]]));
    }

    public function actionIeltsInfoDetail()
    {
        $id = \Yii::$app->request->get('id',1);
        $detail = Info::find()->asArray()->where('id='.$id)->one();
        if($detail!=false){
            Info::updateAll(['viewCount' => ($detail['viewCount'] + 1),'count' => ($detail['count'] + 1)], "id=$id");
        }
        $detail['content']=str_replace('/files/','http://www.thinkuprep.com/files/',$detail['content']);
        $time=time();
        $recommend = Info::find()->asArray()->where('cate=1  and pushTime<='.$time)->orderBy('sort asc,id desc')->limit(5)->all();
        die(json_encode(['data'=>['detail'=>$detail,'recommend'=>$recommend],'code'=>1]));
    }

    /**
     * [actionLogin 模拟登陆]
     * @Author don
     * @Date   2021-08-04
     * @return [type]     [description]
     */
    public function actionUnifyLogin()
    {
        Yii::$app->session->set('uid', 3);
        Yii::$app->session->set('userId', 4);
        $userData = User::find()->where(['uid'=>3])->asArray()->one();
        Yii::$app->session->set('userData', $userData);
        echo "1";
    }

    /**
     * [actionBuyNow 商品信息]
     * @Author don
     * @Date   2021-09-26
     * @return [type]     [description]
     */
    public function actionBuyNow()
    {
        $goodsId = Yii::$app->request->post('id');
        $num = Yii::$app->request->post('num');
        $goods = Classes::find()->asArray()->where('id='.$goodsId)->all();
        $totalMoney = $goods[0]['price'] * $num;
        $goods[0]['num'] = $num;
        $goods[0]['image'] = $goods[0]['pic'];
        $goods[0]['contentName'] = $goods[0]['name'];
        $goods[0]['tag'] = null;
        $goods[0]['contentId'] = $goods[0]['id'];
        $goods[0]['catName'] = $goods[0]['summary'];

        $data = ['typeUrl' => 'newIeltsUrl', 'type' => 12, 'totalMoney' => $totalMoney, 'goods' => $goods];

        $re = ['code' => 1, 'data' => serialize($data)];
        die(json_encode($re));
    }

    /**
     * [actionUpCenter 修改用户信息]
     * @Author don
     * @Date   2021-09-27
     * @return [type]     [description]
     */
    public function actionUpdateUser()
    {
        $uid = Yii::$app->session->get('uid');

        $image = Yii::$app->request->post('image', '');
        $userName = Yii::$app->request->post('userName', '');
        $nickname = Yii::$app->request->post('nickname', '');
        $address = Yii::$app->request->post('address', '');
        $phone = Yii::$app->request->post('phone', '');
        $email = Yii::$app->request->post('email', '');
        $school = Yii::$app->request->post('school', '');
        $education = Yii::$app->request->post('education', '');

        if ($phone && !preg_match("/^1[34578]\d{9}$/", $phone)) {
            die(json_encode(['code'=>0, 'message'=>'手机格式错误！']));
        }

        if ($email && !preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
            die(json_encode(['code'=>0, 'message'=>'邮箱格式错误！']));
        }

        $sign = User::updateAll([
            'image' => $image,
            'address' =>json_encode($address),
            'userName' => $userName,
            'phone' => $phone,
            'nickname' => $nickname,
            'email' => $email,
            'school' => $school,
            'education' => $education
        ], "uid=$uid");

        if (!$sign) {
            die(json_encode(['code'=>0, 'message'=>'修改失败，请重试！']));
        }
        $userData = User::find()->where(['uid'=>$uid])->asArray()->one();
        Yii::$app->session->set('userData', $userData);
        // todo 用户中心修改昵称
        uc_user_nickname_edit($userData['nickname'], $uid);

        die(json_encode(['code'=>1, 'message'=>'修改成功！']));
    }

    /**
     * [actionUpdatePassword 修改密码]
     * @Author don
     * @Date   2021-09-27
     * @return [type]     [description]
     */
    public function actionUpdatePassword()
    {
        $password = Yii::$app->request->post('password');
        $phone = Yii::$app->request->post('phone');
        $phonecode =Yii::$app->request->post('phonecode');
        if (!$password) {
            $res['code'] = 0;
            $res['message'] = '请输入新密码！';
            die(json_encode($res));
        }
        $status = uc_user_checkphone($phone);
        // 手机号不存在， 就 是未注册
        if ($status == 1) {
            $res['code'] = 0;
            $res['message'] = '手机号码未注册！';
            die(json_encode($res));
        }
        $login = new Login();
        // 验证码是否过期
        $checkTime = $login->checkTime();
        if (!$checkTime) {
            $res['code'] = 0;
            $res['message'] = '验证码已过期！';
            die(json_encode($res));
        }
        // 验证码是否正确
        $checkCode = $login->checkCode($phone, $phonecode);
        if (!$checkCode) {
            $res['code'] = 0;
            $res['message'] = '验证码错误！';
            die(json_encode($res));
        }
        // 修改手机和密码todo
        uc_user_phone_edit($phone,$password);

        $res['code'] = 1;
        $res['message'] = '修改成功！';
        Yii::$app->session->remove($phone.'phoneCode');
        die(json_encode($res));
    }

    /**
     * [actionMessage 获取消息]
     * @Author don
     * @Date   2021-10-08
     * @return [type]     [description]
     */
    public function actionGetMessage()
    {
        $uid = Yii::$app->session->get('uid');
        if (!$uid) {
            die(json_encode(['code'=>5, 'message'=>'未登录！']));
        }
        $page = Yii::$app->request->get('page', 1);
        $pageSize = Yii::$app->request->get('pageSize', 10);
        $status = Yii::$app->request->get('status', ''); // 1未读 2已读

        // 查询用户的消息
        $data = News::getAllNews($status, $uid, $page, $pageSize);

        die(json_encode(['code'=>1, 'data'=>$data]));
    }

    /**
     * [actionCheckMessage description]
     * @Author don
     * @Date   2021-10-28
     * @return [type]     [description]
     */
    public function actionCheckMessage()
    {
        $uid = Yii::$app->request->post('uid');
        $id = Yii::$app->request->post('id'); // 考点id

        // 查询发送记录 单个考场一个用户只能发送两次并且满足间隔30分钟
        $count = ExamMessage::find()->where(['uid'=>$uid, 'examId'=>$id])->count();
        if ($count >= 2) {
            $res['code'] = 0;
            $res['message'] = '用户每个考点信息只能发送两次！';
            die(json_encode($res));
        }
        if ($count == 1) {  // 已经发送一条，再发送第二条的时候需要间隔30分钟
            $examMessage = ExamMessage::find()->where(['uid'=>$uid, 'examId'=>$id])->asArray()->one();
            if (time()-$examMessage['createTime'] < 1800) {
                $res['code'] = 0;
                $res['message'] = '考点短信发送间隔需要30分钟！';
                die(json_encode($res));
            }
        }
        // 存考点短信发送记录
        $model = new ExamMessage();
        $model->examId = $id;
        $model->uid = $uid;
        $model->createTime = time();
        if (!$model->save()) {
            $res['code'] = 0;
            $res['message'] = '考点短信发送记录保存失败！';
            die(json_encode($res));
        }

        $data = Examroom::find()->asArray()->where("id=$id")->one();//考点信息

        die(json_encode(['code'=>1, 'data'=>$data]));
    }

    /**
     * TODO-按照申友Lee需求-大首页数据改为以下
     * @Author: Ferre
     * @create: 2021/12/22 10:50
     */
    public function actionHomeInitData()
    {
        $time = time();
        $banner = Banner::find()->asArray()->limit(5)->where("cate=1 and type=1")->orderBy('sort asc,id desc')->all();  //banner
        $info = Info::find()->asArray()->where("(pushTime<=$time or pushTime is null) and cate=1")->limit(12)->orderBy('id desc')->all();    //资讯
        $class = Classes::find()->asArray()->where("id in (504,501,511)")->all();//课程
        $open = Active::find()->asArray()->limit(2)->orderBy('id desc')->all();//公开课活动
        $company = Info::find()->asArray()->where("(pushTime<=$time or pushTime is null) and cate=3")->limit(4)->orderBy('id desc')->all();    //企业动态
        die(json_encode(['code' => 1, 'data' => [
            'banner'  => $banner,
            'info'    => $info,
            'class'   => $class,
            'open'    => $open,
            'company' => $company,
        ]]));
    }

    /**
     * 雷哥雅思课程页
     */
    public function actionIeltsCourse(){
        $type = Yii::$app->request->post('type');
        $model = new Teachers();
        $teachers = $model->getTeacherList(3);
        if ($teachers&&$type) {
            foreach ($teachers as $k => $v) {
                if ($v['url']) {
                    $res = json_decode(Method::post('https://live.thinkwithu.com/api/play/pc-video',['word'=>$v['url']]), true);
                    if ($res['code'] == 1) {
                        $teachers[$k]['url'] = $res['data']['video'];
                    }
                }
            }
        }
        die(json_encode(['data'=>$teachers,'code'=>1]));
    }

    /**
     * 雷哥雅思选课中心
     */
    public function actionIeltsCourseList(){
        $id = Yii::$app->request->get('id');
        $idArr = explode(',',$id);
        $class = [];
        $classData = Classes::classData();
        foreach ($idArr as $k=>$v){
            $where = 'classesPort=1';
            if($v) $where .= " and cate={$v}";
            $tmp = Classes::find()->asArray()->where($where)->orderBy('sort asc,id desc')->all();
            foreach ($tmp as $k2=>$v2){
                $tmp[$k2]['classType'] = isset($classData['classType'][$v2['class']])?$classData['classType'][$v2['class']]:'';
            }
            $class[$k] = $tmp;
        }
        die(json_encode(['data'=>$class,'code'=>1]));
    }

    /**
     * 雷哥雅思课程详情
     */
    public function actionIeltsCourseDetail(){
        $id = \Yii::$app->request->get('id');
        $class=Classes::find()->asArray()->where('id='.$id)->one();
        $class['systemPeople']= explode(PHP_EOL,$class['systemPeople']);
        $class['systemContent']= explode(PHP_EOL,$class['systemContent']);
        $class['systemCourse']= explode(PHP_EOL,$class['systemCourse']);
        $class['systemServe']= explode(PHP_EOL,$class['systemServe']);
        if($class['systemTeacher']){
            $str = $class['systemTeacher'];
            $class['systemTeacher'] = Teachers::find()->where("id in ($str)")->asArray()->all();
        }else{
            $class['systemTeacher']=[];
        }

        if($class!=false){
            Classes::updateAll(['viewCount' => ($class['viewCount'] + 1)], "id=$id");
        }
        $classData = Classes::classData();
        $class['classType'] = isset($classData['classType'][$class['class']])?$classData['classType'][$class['class']]:'';
        $class['courseType'] = isset($classData['courseType'][$class['cate']])?$classData['courseType'][$class['cate']]:'';
        $model=new Teachers();
        $class['teachers'] =$model->getTeachers($class['teacher']);
        // 处理视频sdk
        $res = json_decode(Method::curl_post_fix('https://live.thinkwithu.com/api/play/pc-video',['word'=>$class['url']]), true);
        if ($res['code'] == 1) {
            $class['url'] = $res['data']['video'];
        }
        die(json_encode(['data'=>$class,'code'=>1]));
    }

    /***
     * 上传音频
     */
    public function actionUpload()
    {
        if(!$_FILES){
            die(json_encode(['code'=>0,'message'=>'请先选择音频！']));
        }
        $file = $_FILES["file"];
        $dir = 'files/listen/audio/';
        $file_path = $dir.$_FILES["file"]["name"];
        $domain = Yii::$app->request->hostInfo;
        if(is_file($file_path)){
            die(json_encode(['code'=>2,'message'=>'上传成功！','data'=>'/'.$file_path,'domain'=>$domain]));
        }

        $upload = new UploadFile();

        $upload->int_max_size = 31457280;

        $upload->arr_allow_exts = array('mp3', 'wav', 'wma', 'mov');

        $upload->str_save_path = $dir;

        $upload->str_save_rule = '';

        $arr_rs = $upload->upload($file);

        if ($arr_rs['int_code'] == 1) {
            $filePath = '/' . $dir . $arr_rs['arr_data']['arr_data'][0]['savename'];
            $res['code'] = 1;
            $res['message'] = '上传成功';
            $res['data'] = $filePath;
            $res['domain'] = $domain;
        } else {
            $message = '上传失败';
            if($arr_rs['arr_data']['int_error']==8){
                $message = '文件大小超过限制';
            }elseif($arr_rs['arr_data']['int_error']==10){
                $message = '文件格式不正确';
            }
            $res['code'] = 0;
            $res['message'] = $message;
        }
        die(json_encode($res));
    }

    public function actionWrite()
    {
        $answer='This summer holiday I plan to go to the beach. I will go there with my parents and cousins. Well stay there for three days at the local hotel. The trip will be the most wonderful one that I have ever had. Because we will do a lot of things there, such as playing volleyball, windsurfing, having barbecue at night. Im really looking foward to it.';
        $remark = Write::writeCorrect($answer, 1, 'ielts');
        $res = json_decode($remark, true);
        die(json_encode($res));
    }

    public function actionSpoken()
    {
        $file = \Yii::$app->request->get('file');
        $text = \Yii::$app->request->get('text');
        $speak = new Speak();
        $res = $speak->xfyun($file, $text);
        die(json_encode($res));
    }
}
